<template>
  <div class="create-paper-container">
    <!-- 头部 -->
    <header class="create-header">
      <el-steps
        :active="activeStep"
        finish-status="success"
        simple
      >
        <el-step title="基本信息" />
        <el-step title="关联试卷" />
      </el-steps>
    </header>

    <!-- 内容区 -->
    <div class="create-content">
      <main v-if="activeStep === 0">
        <!-- 第一步 基本信息 -->
        <div class="content-wrapper">
          <h2 class="form-title">基本信息</h2>
          <el-form
            :model="formData"
            ref="formRef"
            label-width="100px"
            class="form-container"
          >
            <el-form-item label="试卷名称" prop="paperName" :rules="rules.paperName">
              <el-input v-model="formData.paperName" placeholder="请输入试卷名称" />
            </el-form-item>

            <el-form-item 
              label="试卷类型" 
              prop="paperType"
              :rules="rules.paperType"
            >
              <el-radio-group v-model="formData.paperType" disabled>
                <el-radio label="dailyPractice">每日一练</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="业务类型" prop="businessType" :rules="rules.businessType">
              <el-cascader
                v-model="formData.businessType"
                :options="businessTypeOptions"
                :props="{
                  checkStrictly: false,
                  emitPath: true,
                  expandTrigger: 'hover'
                }"
                placeholder="请选择业务类型"
                clearable
              />
            </el-form-item>

            <el-form-item 
              label="试卷备注" 
              prop="remarks"
            >
              <template #label>
                <span style="display: inline-block; width: 8px; margin-right: 4px;">&nbsp;</span>
                试卷备注
              </template>
              <el-input 
                v-model="formData.remarks"
                type="textarea"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-form>
        </div>
      </main>

      <main v-else-if="activeStep === 1">
        <!-- 第二步 关联试卷 -->
        <div class="content-wrapper">
          <h2 class="form-title">关联信息</h2>
          <el-form :model="formData" label-width="100px" class="form-container">
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item label="出题类型">
                  <el-radio-group v-model="formData.questionType">
                    <el-radio :label="'manual'" :disabled="false">人工选题</el-radio>
                    <el-radio :label="'random'" :disabled="true">随机选题</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12" class="add-question-col">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="openQuestionDrawer"
                  v-if="formData.questionType === 'manual'"
                >
                  <el-icon><Plus /></el-icon>添加试题
                </el-button>
              </el-col>
            </el-row>

            <div v-if="formData.questionType === 'manual'" class="manual-questions">
              <div class="selected-questions-wrapper">
                <div class="questions-list">
                  <el-table 
                    :data="selectedQuestions" 
                    style="width: 100%"
                    border
                    height="400"
                  >
                    <el-table-column type="index" label="序号" width="60" align="center" />
                    <el-table-column prop="qsContent" label="题面" min-width="180" show-overflow-tooltip>
                      <template #default="{ row }">
                        <div v-html="row.qsContent"></div>
                      </template>
                    </el-table-column>
                    <el-table-column prop="busiTypeName1" label="一级分类" width="120" />
                    <el-table-column prop="busiTypeName2" label="二级分类" width="140" />
                    <el-table-column prop="busiTypeName3" label="三级分类" width="120" />
                    <el-table-column prop="questionType" label="题型" width="100">
                      <template #default="{ row }">
                        <el-tag :type="getQuestionTypeTag(row.questionType)">
                          {{ mapQuestionType(row.questionType) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column 
                      label="等级" 
                      prop="level" 
                      width="100"
                    >
                      <template #default="{ row }">
                        <el-tag :type="getDifficultyTag(row.level)">
                          {{ mapDifficulty(row.level) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="分数" width="120" align="center">
                      <template #default="{ row }">
                        <el-input-number
                          v-model="row.score"
                          :min="0"
                          :max="100"
                          size="small"
                          :controls="false"
                          style="width: 80px"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" fixed="right">
                      <template #default="{ $index }">
                        <el-button
                          type="danger"
                          link
                          @click="removeQuestion($index)"
                        >
                          删除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </div>
          </el-form>
        </div>
      </main>
    </div>

    <!-- 添加试题抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="添加试题"
      :size="drawerSize"
      direction="rtl"
      :destroy-on-close="true"
    >
      <template #header>
        <div class="drawer-header">
          <h3>添加试题</h3>
        </div>
      </template>
      
      <div class="drawer-content">
        <!-- 试题包展示区域 -->
        <div class="question-packages">
          <div class="packages-container">
            <!-- 添加左右滚动按钮 -->
            <div 
              class="scroll-button left" 
              v-show="canScrollLeft"
              @click="scrollPackages('left')"
            >
              <el-icon><ArrowLeft /></el-icon>
            </div>
            
            <div class="scroll-button right" 
              v-show="canScrollRight"
              @click="scrollPackages('right')"
            >
              <el-icon><ArrowRight /></el-icon>
            </div>

            <div class="packages-wrapper" ref="packagesWrapper">
              <div class="packages-row">
                <div 
                  v-for="pkg in questionPackages" 
                  :key="pkg.id"
                  class="package-item"
                >
                  <el-card 
                    class="package-card" 
                    :class="{ 'is-active': selectedPackage === pkg.name }"
                    @click="selectPackage(pkg)"
                  >
                    <div class="package-info">
                      <div class="package-icon">
                        <el-icon :size="20"><Document /></el-icon>
                      </div>
                      <div class="package-content">
                        <h4 class="package-name">{{ pkg.name }}</h4>
                        <div class="package-meta">
                          <el-tag size="small" :type="getPackageTypeTag(pkg.type)">
                            {{ pkg.type }}
                          </el-tag>
                          <span class="question-count">
                            <el-icon><Collection /></el-icon>
                            {{ pkg.questionCount }}题
                          </span>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 试题列表区域 -->
        <div class="questions-container" v-if="selectedPackage">
          <div class="section-title">
            <h4>试题列表</h4>
            <el-button type="primary" size="small" @click="addSelectedQuestions">
              添加所选试题
            </el-button>
          </div>
          
          <div class="table-container">
            <el-table
              ref="questionTable"
              :data="currentPackageQuestions"
              @selection-change="handleSelectionChange"
              style="width: 100%"
              height="calc(100% - 20px)"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column 
                label="题面" 
                prop="qsContent" 
                min-width="200" 
                show-overflow-tooltip
              />
              <el-table-column 
                label="答案" 
                prop="qsCorrectAns" 
                width="120"
                show-overflow-tooltip
              >
                <template #default="{ row }">
                  {{ formatAnswer(row.qsCorrectAns, row.questionType) }}
                </template>
              </el-table-column>
              <el-table-column 
                label="题型" 
                prop="questionType" 
                width="100"
              >
                <template #default="{ row }">
                  <el-tag :type="getQuestionTypeTag(row.questionType)">
                    {{ mapQuestionType(row.questionType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column 
                label="等级" 
                prop="level" 
                width="100"
              >
                <template #default="{ row }">
                  <el-tag :type="getDifficultyTag(row.level)">
                    {{ mapDifficulty(row.level) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 底部 -->
    <footer class="create-footer">
      <div class="footer-content">
        <div class="left-content">
          <div class="score-info" v-if="activeStep === 1 && selectedQuestions.length > 0">
            <span class="score-item">
              <span class="score-label">总分:</span>
              <span class="score-value total-score">{{ totalManualScore }}</span>
            </span>
            <span class="score-item">
              <span class="score-label">及格分数:</span>
              <el-input-number
                :controls="false"
                v-model="formData.manualPassingScore"
                :min="0"
                :max="totalManualScore"
                :step="1"
                controls-position="right"
                size="small"
                @change="handlePassingScoreChange"
                placeholder="请输入及格分数"
                :required="true"
              />
            </span>
            <span class="score-item" v-if="formData.manualPassingScore > 0">
              <span class="score-label">及格线:</span>
              <span class="score-value passing-rate">
                {{ Math.round((formData.manualPassingScore / totalManualScore) * 100) }}%
              </span>
            </span>
          </div>
        </div>
        <div class="right-content">
          <el-button @click="close" size="small">关闭</el-button>
          <div class="right-buttons">
            <el-button 
              v-if="activeStep === 1" 
              @click="prevStep" 
              size="small"
            >上一步</el-button>
            <el-button 
              type="primary" 
              @click="nextStep" 
              size="small"
            >{{ activeStep === 0 ? "下一步" : "完成" }}</el-button>
          </div>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import { getExamPaperDetail, createExamPaper, updateExamPaper,getAllExamPaperPackages ,getExamPaperPackageDetail } from '@/api/api';
import { Document, Collection, Plus, ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

// 获取路由和路由器实例
const route = useRoute();
const router = useRouter();

// 跟踪模式和试卷ID
const mode = ref(route.query.mode || 'create');
const paperId = ref(route.query.paperId || null);

// 添 paperData 的定义
const paperData = ref(null);

// 表单数据
const formData = ref({
  id: null,
  paperName: "",
  paperType: "dailyPractice",
  businessType: [],
  remarks: "",
  questionType: "manual",
  manualPassingScore: 0,
});

// 选试题列表（主列表）
const selectedQuestions = ref([]);

// 计算人工出题的总分
const totalManualScore = computed(() => {
  return selectedQuestions.value.reduce((sum, question) => sum + question.score, 0);
});

// 初始化编辑数据
const initEditData = async () => {
  if (!paperId.value) return;
  try {
    const response = await getExamPaperDetail(paperId.value);
    if (response.code === 200) {
      const data = response.data;
      // 保存原始试卷数据，用于后续比较
      paperData.value = data;
      
      formData.value = {
        id: data.paperId,
        paperName: data.paperName,
        paperType: "dailyPractice",
        businessType: [
          data.busiTypeId1,
          data.busiTypeId2,
          data.busiTypeId3
        ].filter(Boolean),
        remarks: data.description || '',
        questionType: 'manual',  // 强制设置为人工选题
        manualPassingScore: data.passScore
      };

      selectedQuestions.value = data.questions.map(question => ({
        id: question.questionId || question.id,
        questionId: question.questionId || question.id,
        qsContent: question.qsContent,
        questionType: question.questionType,
        level: question.level,
        score: question.score || 0,
        busiTypeName1: question.busiTypeName1,
        busiTypeName2: question.busiTypeName2,
        busiTypeName3: question.busiTypeName3,
        orderNumber: question.questionOrder || question.orderNumber
      }));
    } else {
      ElMessage.error(response.message || '获取试卷详情失败');
    }
  } catch (error) {
    console.error('获取试卷详情失败:', error);
    ElMessage.error('获试卷详情失败');
  }
};

// 监听路由参数变化
watch(
  () => route.query,
  async (newQuery) => {
    mode.value = newQuery.mode || 'create';
    paperId.value = newQuery.paperId || null;
    if (mode.value === 'edit' && paperId.value) {
      await initEditData();
    } else {
      // 重置数据
      paperData.value = null;
      formData.value = {
        id: null,
        paperName: "",
        paperType: "dailyPractice",
        businessType: [],
        remarks: "",
        questionType: "manual",
        manualPassingScore: 0,
      };
      selectedQuestions.value = [];
    }
  },
  { immediate: true }
);

// 当前步骤
const activeStep = ref(0);
// 总分
const totalScore = ref(0);

const calculateTotalScore = () => {
  totalScore.value = questionRules.value.reduce((sum, rule) => {
    return (
      sum +
      rule.primary * rule.score +
      rule.intermediate * rule.score +
      rule.advanced * rule.score
    );
  }, 0);
};

// 业务型数据（示例）
const businessTypeOptions = [
  {
    value: 1,
    label: "计算机学院",
    children: [
      {
        value: 11,
        label: "基础课程",
        children: [
          { value: 111, label: "计算机基础" },
          { value: 112, label: "程序设计" }
        ]
      },
      {
        value: 12,
        label: "专业课程",
        children: [
          { value: 121, label: "数据结构" },
          { value: 122, label: "操作系统" },
          { value: 123, label: "算机网络" }
        ]
      }
    ]
  },
  {
    value: 2,
    label: "电子信息学院",
    children: [
      {
        value: 21,
        label: "基础课程",
        children: [
          { value: 211, label: "电路基础" },
          { value: 212, label: "模拟电子技术" }
        ]
      },
      {
        value: 22,
        label: "专业课程",
        children: [
          { value: 221, label: "数字电路" },
          { value: 222, label: "信号处理" }
        ]
      }
    ]
  }
]

// 随机出题规则数据
const questionRules = ref([
  { type: "单选", primary: 0, intermediate: 0, advanced: 0, score: 0 },
  { type: "多选题", primary: 0, intermediate: 0, advanced: 0, score: 0 },
  { type: "判断题", primary: 0, intermediate: 0, advanced: 0, score: 0 },
]);

// 引用 ElForm 实例
const formRef = ref(null);

const drawerVisible = ref(false)

// 计算抽屉宽度
const drawerSize = computed(() => {
  return `${(window.innerWidth * 2) / 3}px`
})

// 打开抽屉
const openQuestionDrawer = () => {
  drawerVisible.value = true
}

// 选择出题类型
const selectQuestionType = (type) => {
  formData.value.questionType = type
  if (type === 'manual') {
    selectedQuestions.value = []
  }
}

// 修改关闭按钮的处理函数
const close = () => {
  ElMessageBox.confirm(
    '关闭页面将丢失未保存的内容，是否继续？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 确认关闭，返回列表页
      router.push({ name: 'list' })
    })
    .catch(() => {
      // 取消关闭，保持当前页面
    })
}

// 上一步按
const prevStep = () => {
  if (activeStep.value > 0) {
    activeStep.value -= 1;
  }
};

// 获取题型对应的标签类型
const getQuestionTypeTag = (type) => {
  const map = {
    'radio': '',
    'checkbox': 'success',
    'judge': 'info',
    'fill': 'warning'
  }
  return map[type] || ''
}

// 获取难度等级对应的标签类型
const getDifficultyTag = (level) => {
  const map = {
    1: 'info',
    2: 'warning',
    3: 'danger'
  }
  return map[level] || ''
}

// 删除试题
const removeQuestion = (index) => {
  ElMessageBox.confirm(
    '确定要删除这道试题吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    selectedQuestions.value.splice(index, 1)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 试题包数据
const questionPackages = ref([])
const currentPackageQuestions = ref([])
const selectedPackage = ref(null)
const tempSelectedQuestions = ref([])

// 获取试题包列表
const fetchQuestionPackages = async () => {
  try {
    const response = await getAllExamPaperPackages()
    console.log('获取试题包列表响应:', response)
    if (response.code === 200) {
      // 确保数据格式正确
      questionPackages.value = response.data.map(pkg => ({
        id: pkg.id,
        name: pkg.packName || '未命名试题包',
        type: pkg.busiTypeName1 || '未分类',
        questionCount: pkg.questionCount || 0
      }))
      console.log('处理后的试题包列表:', questionPackages.value)
    } else {
      ElMessage.error(response.message || '获取试题包列表失败')
    }
  } catch (error) {
    console.error('获取试题包列表失败:', error)
    ElMessage.error('获取试题包列表失败')
  }
}

// 选择试题包并获取详情
const selectPackage = async (pkg) => {
  console.log('选择试题包:', pkg)
  selectedPackage.value = pkg.name
  try {
    const params = {
      packageName: pkg.name
    }
    const response = await getExamPaperPackageDetail(params)
    console.log('获取试题包详情响应:', response)
    
    // 检查响应数据结构
    if (response.code === 200) {
      let questions = []
      
      // 尝试不同的数据路径
      if (Array.isArray(response.data)) {
        questions = response.data
      } else if (response.data && Array.isArray(response.data.questions)) {
        questions = response.data.questions
      } else if (response.data && response.data.questionList) {
        questions = response.data.questionList
      }
      
      console.log('解析出的试题列:', questions)
      
      if (questions.length > 0) {
        currentPackageQuestions.value = questions.map(question => ({
          id: question.id,
          qsContent: question.qsContent || question.content || '',
          questionType: question.questionType || question.type || 'unknown',
          level: question.level || question.difficulty || 1,
          qsCorrectAns: question.qsCorrectAns || question.correctAnswer || '',
          // 保存完整的业务类型信息
          busiTypeId1: question.busiTypeId1,
          busiTypeName1: question.busiTypeName1,
          busiType1: question.busiType1,
          busiTypeId2: question.busiTypeId2,
          busiTypeName2: question.busiTypeName2,
          busiTypeId3: question.busiTypeId3,
          busiTypeName3: question.busiTypeName3,
          // 添加备用字段映射
          ...(question.busiTypeName1 ? {} : {
            busiTypeName1: question.categoryLevel1,
            busiTypeName2: question.categoryLevel2,
            busiTypeName3: question.categoryLevel3
          })
        }));
        console.log('处理后的试题列表:', currentPackageQuestions.value);
      } else {
        ElMessage.warning('试题包中没有试题');
        currentPackageQuestions.value = [];
      }
    } else {
      ElMessage.error(response.message || '获取试题包详情失败')
    }
  } catch (error) {
    console.error('获取试题包详情失败:', error)
    ElMessage.error('获取试题包详情失败')
  }
}

// 修改题型映射函数
const mapQuestionType = (type) => {
  const typeMap = {
    'radio': '单选题',
    'checkbox': '多选题',
    'judge': '判断题',
    'fill': '填空题'
  }
  return typeMap[type] || '未知类型'
}

// 修改难度映射函数
const mapDifficulty = (level) => {
  const difficultyMap = {
    1: '初级',
    2: '中级',
    3: '高级'
  }
  return difficultyMap[level] || '未知难度'
}

// 修改添加选中试题的逻辑
const addSelectedQuestions = () => {
  console.log('准备添加选中的试题:', tempSelectedQuestions.value);
  
  // 检查是否有重复试题
  const newQuestions = tempSelectedQuestions.value.filter(
    newQuestion => !selectedQuestions.value.some(
      existingQuestion => existingQuestion.id === newQuestion.id
    )
  );
  
  if (newQuestions.length === 0) {
    ElMessage.warning('所选试题已存在，请勿重复添加');
    return;
  }

  // 为新添加的试题设置默认分数为0，并保留完整的业务类型信息
  const questionsWithScore = newQuestions.map(question => ({
    id: question.id,
    questionId: question.id,
    qsContent: question.qsContent,
    questionType: question.questionType,
    level: question.level,
    score: 0,
    // 确保保留完整的业务类型信息
    busiTypeId1: question.busiTypeId1,
    busiTypeName1: question.busiTypeName1 || question.categoryLevel1,
    busiType1: question.busiType1,
    busiTypeId2: question.busiTypeId2,
    busiTypeName2: question.busiTypeName2 || question.categoryLevel2,
    busiTypeId3: question.busiTypeId3,
    busiTypeName3: question.busiTypeName3 || question.categoryLevel3
  }));

  console.log('处理后准备添加的试题:', questionsWithScore);

  selectedQuestions.value = [
    ...selectedQuestions.value,
    ...questionsWithScore
  ];
  
  ElMessage.success(`成功添加 ${newQuestions.length} 道试题`);
  drawerVisible.value = false;
  tempSelectedQuestions.value = [];
};

// 计算人工选题模式下的总分
const calculateTotalManualScore = () => {
  totalManualScore.value = selectedQuestions.value.reduce(
    (sum, question) => sum + question.score, 
    0
  )
}

// 在组件挂载时获取试题包列表
onMounted(() => {
  fetchQuestionPackages()
})

// 获取试题包类型对应的标签类型
const getPackageTypeTag = (type) => {
  const map = {
    '编程语言': 'success',
    '计算机基础': 'info',
    '专业课程': 'warning',
    '前端开发': ''
  }
  return map[type] || 'info'
}

// 选中试题变化处理
const handleSelectionChange = (selection) => {
  console.log('选中的试题变化:', selection)
  tempSelectedQuestions.value = selection
}

// 添加滚动相关的逻辑
const packagesWrapper = ref(null)
const canScrollLeft = ref(false)
const canScrollRight = ref(true)

// 检查是否可以滚动
const checkScroll = () => {
  if (!packagesWrapper.value) return
  const { scrollLeft, scrollWidth, clientWidth } = packagesWrapper.value
  canScrollLeft.value = scrollLeft > 0
  canScrollRight.value = scrollLeft < scrollWidth - clientWidth
}

// 滚动试题包列表
const scrollPackages = (direction) => {
  if (!packagesWrapper.value) return
  const scrollAmount = 300 // 每次滚动的距离
  const currentScroll = packagesWrapper.value.scrollLeft
  const newScroll = direction === 'left' 
    ? currentScroll - scrollAmount 
    : currentScroll + scrollAmount
    
  packagesWrapper.value.scrollTo({
    left: newScroll,
    behavior: 'smooth'
  })
  
  // 滚动后更新按钮状态
  setTimeout(checkScroll, 300)
}

// 监听滚动事件
onMounted(() => {
  if (packagesWrapper.value) {
    packagesWrapper.value.addEventListener('scroll', checkScroll)
    // 初始检查
    checkScroll()
  }
})

// 添加处理及格分数变化的方法
const handlePassingScoreChange = (value) => {
  if (!value && value !== 0) {
    formData.value.manualPassingScore = 0;
    ElMessage.warning('请设置及格分数');
    return;
  }

  if (value < 0) {
    formData.value.manualPassingScore = 0;
    ElMessage.warning('及格分数不能小于0');
    return;
  }

  if (value > totalManualScore.value) {
    formData.value.manualPassingScore = totalManualScore.value;
    ElMessage.warning('及格分数不能超过总分');
    return;
  }
}

// 添加业务类型验证规则
const rules = ref({
  paperName: [
    { required: true, message: '请输入试卷名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  paperType: [
    { required: true, message: '请选择试卷类型', trigger: 'change' }
  ],
  businessType: [
    { 
      required: true, 
      type: 'array',
      message: '请选择完的业务类型',
      trigger: 'change',
      validator: (rule, value) => {
        return value && value.length === 3
      }
    }
  ],
  remarks: []
})

// 添加查找节点的辅助函数
const findNodeById = (nodes, id) => {
  if (!nodes) return null
  return nodes.find(node => node.value === id)
}

// 添加 emit 定义
const emit = defineEmits(['create-success'])

// 添加答案格式化函数
const formatAnswer = (answer, type) => {
  if (type === 'judge') {
    return answer === 'true' ? '正确' : '错误'
  }
  return answer
}

// 修改 nextStep 方法
const nextStep = async () => {
  if (activeStep.value === 0) {
    try {
      await formRef.value?.validate();
      if (formData.value.businessType.length !== 3) {
        ElMessage.warning('请选择完整的业务类型（需要选择到第三级）');
        return;
      }
      activeStep.value = 1;
    } catch (error) {
      console.error('表单验证失败:', error);
      return;
    }
  } else if (activeStep.value === 1) {
    // 验证试题
    if (formData.value.questionType === 'manual' && selectedQuestions.value.length === 0) {
      ElMessage.warning('请至少选择一道试题');
      return;
    }

    // 检查试题分数
    const zeroScoreQuestions = selectedQuestions.value.filter(q => !q.score || q.score === 0);
    if (zeroScoreQuestions.length > 0) {
      ElMessage.error(`有 ${zeroScoreQuestions.length} 道试题未设置分数，请设置所有试题的分数`);
      return;
    }

    // 检查及格分数
    if (!formData.value.manualPassingScore) {
      ElMessage.warning('请设置及格分数');
      return;
    }

    // 检查及格分数是否超过总分
    if (formData.value.manualPassingScore > totalManualScore.value) {
      ElMessage.warning('及格分数不能超过总分');
      return;
    }

    try {
      const [busiTypeId1, busiTypeId2, busiTypeId3] = formData.value.businessType;
      const selectedNode1 = findNodeById(businessTypeOptions, busiTypeId1);
      const selectedNode2 = findNodeById(selectedNode1?.children || [], busiTypeId2);
      const selectedNode3 = findNodeById(selectedNode2?.children || [], busiTypeId3);

      // 构造基础提交数据
      const submitData = {
        paperId: mode.value === 'edit' ? paperId.value : undefined,
        paperName: formData.value.paperName,
        busiTypeId1: busiTypeId1,
        busiTypeName1: selectedNode1?.label,
        busiType1: selectedNode1?.value?.toString().toLowerCase(),
        busiTypeId2: busiTypeId2,
        busiTypeName2: selectedNode2?.label,
        busiTypeId3: busiTypeId3,
        busiTypeName3: selectedNode3?.label,
        paperType: 1,
        questionType: formData.value.questionType === 'manual' ? 1 : 2,
        unifyPaper: 1,
        questionOrder: 1,
        description: formData.value.remarks || '',
        totalScore: Number(totalManualScore.value).toFixed(2),
        passScore: Number(formData.value.manualPassingScore).toFixed(2),
        passScoreRate: (formData.value.manualPassingScore / totalManualScore.value).toFixed(1),
        questions: {  // 使用新的 questions 结构
          add: [],
          update: [],
          delete: []
        }
      };

      if (mode.value === 'edit') {
        // 编辑模式：需要处理试题的增删改
        const originalQuestionMap = new Map(
          (paperData.value?.questions || []).map(q => [
            q.questionId || q.id,
            {
              score: q.score,
              orderNumber: q.orderNumber || q.questionOrder
            }
          ])
        );

        // 处理新增和更新的试题
        selectedQuestions.value.forEach((question, index) => {
          const questionId = question.questionId || question.id;
          const originalQuestion = originalQuestionMap.get(questionId);
          
          if (!originalQuestion) {
            // 新增试题
            submitData.questions.add.push({
              questionId: questionId,
              score: Number(question.score).toFixed(2),
              orderNumber: index + 1
            });
          } else if (
            originalQuestion.score !== question.score ||
            originalQuestion.orderNumber !== (index + 1)
          ) {
            // 更新试题（分数或顺序发生变化）
            submitData.questions.update.push({
              questionId: questionId,
              score: Number(question.score).toFixed(2),
              orderNumber: index + 1
            });
          }
        });

        // 处理删除的试题
        paperData.value?.questions?.forEach(question => {
          const questionId = question.questionId || question.id;
          if (!selectedQuestions.value.some(q => (q.questionId || q.id) === questionId)) {
            submitData.questions.delete.push(questionId);
          }
        });
      } else {
        // 创建模式：所有试题都放在 add 数组中
        submitData.questions.add = selectedQuestions.value.map((q, index) => ({
          questionId: q.questionId || q.id,
          score: Number(q.score).toFixed(2),
          orderNumber: index + 1
        }));
        // update 和 delete 数组保持为空
      }

      console.log('准备提交的数据:', submitData);

      const response = mode.value === 'edit'
        ? await updateExamPaper(paperId.value, submitData)
        : await createExamPaper(submitData);

      if (response.code === 200) {
        ElMessage.success(mode.value === 'edit' ? '试卷更新成功' : '试卷创建成功');
        router.push({ name: 'list' });
      } else {
        ElMessage.error(response.message || (mode.value === 'edit' ? '更新试卷失败' : '创建试卷失败'));
      }
    } catch (error) {
      console.error(mode.value === 'edit' ? '更新试卷失败:' : '创建试卷失败:', error);
      ElMessage.error(mode.value === 'edit' ? '更新试卷失败' : '创建试卷失败');
    }
  }
};
</script>

<style scoped>
@import "../css/create.css";

/* 添加试题包卡片相关样式 */
.package-card {
  margin: 8px;
  cursor: pointer;
  transition: all 0.3s;
}

.package-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
}

.package-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.package-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background-color: #f0f7ff;
  color: #409EFF;
}

.package-content {
  flex: 1;
}

.package-name {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.package-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.question-count {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.is-active {
  border-color: #409EFF;
}

.is-active .package-icon {
  background-color: #409EFF;
  color: #fff;
}
</style>